#include<stdlib.h>
#include<stdio.h>
#include<math.h>

typedef struct node
{
	struct node *next;
	struct node *previous;
	int value;
}*Node;

#define XALLOC(type,size) (type *)malloc(size*sizeof(type))
#define XMEMSET(pointer,type,num) memset(pointer,0,num*sizeof(type))
#define AddMove(previous,toAddNode) do\
	{\
		AddNode(previous,toAddNode);\
		previous = toAddNode;\
	}\
	while(0)

Node NewNode()
{
	Node tempPointer = XALLOC(struct node,1);
	tempPointer->value = 0;
	tempPointer->previous = NULL;
	tempPointer->next = NULL;
	return tempPointer;
}

void AddNode(Node previous,Node toAddNode)
{
	if(previous != NULL && toAddNode != NULL)
	{
		toAddNode->previous = previous;
		toAddNode->next = NULL;
		previous->next = toAddNode;
	}
}

int IsPrimer(int target,Node root)
{
	int result = 1;
	Node p = root;
	Node s = root;

	while(1)
	{
		if(target%p->value == 0)
			return 0;

		p=p->next;
		if(p == NULL)
			break;
		if((p->value) > sqrt((float)target))
			break;
	}
	return result;
}

void DumpList(Node root)
{
	Node p = root;
	int rowNumber=1;
	while(1)
	{
		if(p!=NULL)
		{
			printf("%d\t",p->value);
			p=p->next;
			rowNumber++;
			if(rowNumber == 5)
			{
				printf("\n");
				rowNumber = 1;
			}
		}

		if(p==NULL)
			break;
	}
}

void FreeList(Node root)
{
	Node p = root;
	Node s;
	while(1)
	{
		if(p!=NULL)
		{
			s=p->next;
			free(p);
			p = s;
		}

		if(p==NULL)
			break;
	}
}

int main() 
{ 
	int MainMem[500];
	int num = 2;
	Node root = NewNode();
	root->value = 2;
	Node currentNode = root;
	Node nodeOne = NewNode();
	nodeOne -> value = 3;
	int target = 5;
	AddMove(currentNode,nodeOne);

	MainMem[0]=2;
	MainMem[1]=3;

	while(1)
	{
		if(IsPrimer(target,root) == 1)
		{
			Node tempNode = NewNode();
			tempNode->value = target;
			AddMove(currentNode,tempNode);
			num++;
		}
		target++;

		if(num>=500)
			break;
	}

	DumpList(root);

	FreeList(root);

	return 0; 
} 



/*
Print Table of 500 Primes
Program P
p 148

The idea is :
if the number can not divided by all the primer less than it self, 
the number is primer.
*/
